import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(!"Hikari".equals(username) || !"123".equals(password)) { //反写避免空指针异常
            //登录失败
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户名或密码错误");
            return;
        }
        //登录成功
        HttpSession session = req.getSession(true);//根据Cookie中的SessionId查找Session对象，true：允许无则新建
        //设置/更新会话属性
        session.setAttribute("username", username);
        session.setAttribute("loginTime", System.currentTimeMillis());
        resp.sendRedirect("index");//重定向至index路径（GET）
    }
}
